#include "glwidget.h"
#include <QDebug>
#include <QString>
#include <QOpenGLShaderProgram>
#include "vertex.h"

static const Vertex sg_vertexes[] = {
    Vertex(QVector3D( 0.00f,  0.75f, 1.0f), QVector3D(1.0f, 0.0f, 0.0f)),
    Vertex(QVector3D( 0.75f, -0.75f, 1.0f), QVector3D(0.0f, 1.0f, 0.0f)),
    Vertex(QVector3D(-0.75f, -0.75f, 1.0f), QVector3D(0.0f, 0.0f, 1.0f))
};

GLWidget::GLWidget()
{

}

GLWidget::~GLWidget()
{
    makeCurrent();
    teardownGL();
}


void GLWidget::initializeGL()
{
    /*初始化OpenGL后台*/
    initializeOpenGLFunctions();
    printContextInformation();

    /*设置全局信息*/
    glClearColor(0.0f, 0.0f, 0.0f, 1.0f);

    /*初始化指定应用*/
    /*创建Shader*/
    m_program = new QOpenGLShaderProgram();
    m_program->addShaderFromSourceFile( QOpenGLShader::Vertex, ":/shaders/simple.vert");
    m_program->addShaderFromSourceFile( QOpenGLShader::Fragment, ":/shaders/simple.frag");
    m_program->link();
    m_program->bind();

    /*创建Buffer*/
    m_vertex.create();
    m_vertex.bind();
    m_vertex.setUsagePattern(QOpenGLBuffer::StaticDraw);
    m_vertex.allocate(sg_vertexes, sizeof(sg_vertexes));

    /*创建Vertex Array Object*/
    m_object.create();
    m_object.bind();
    m_program->enableAttributeArray(0);;
    m_program->enableAttributeArray(1);
    m_program->setAttributeBuffer(0, GL_FLOAT, Vertex::positionOffset(), Vertex::PositionTupleSize, Vertex::stride());
    m_program->setAttributeBuffer(1, GL_FLOAT, Vertex::colorOffset(), Vertex::ColorTupleSize, Vertex::stride());

    /*释放资源*/
    m_object.release();
    m_vertex.release();
    m_program->release();
}

void GLWidget::resizeGL(int width, int height)
{
    (void)width;
    (void)height;
}

void GLWidget::paintGL()
{
    /*使用glClearColor设置的颜色来清除背景颜色*/
    glClear(GL_COLOR_BUFFER_BIT);

    /*Render using our shader*/
    m_program->bind();
    m_object.bind();
    glDrawArrays(GL_TRIANGLES, 0, sizeof(sg_vertexes)/sizeof(sg_vertexes[0]));
    m_object.release();
    m_program->release();
}

/**
 * @brief GLWidget::teardownGL  清除资源
 */
void GLWidget::teardownGL()
{
    m_object.destroy();
    m_vertex.destroy();
    delete m_program;
}

/**
 * @brief GLWidget::printContextInformation 打印OpenGL上下文信息
 */
void GLWidget::printContextInformation()
{
    QString type;
    QString version;
    QString profile;

    /*获取OpenGL版本信息*/
    type = (context()->isOpenGLES()) ? "OpenGL ES" : "OpenGL";
    version = reinterpret_cast<const char*>(glGetString(GL_VERSION));

    /*获取OpenGL属性信息*/
#define CASE(c) case QSurfaceFormat::c: profile = #c; break
  switch (format().profile())
  {
    CASE(NoProfile);
    CASE(CoreProfile);
    CASE(CompatibilityProfile);
  }
#undef CASE

    qDebug() << qPrintable(type) << qPrintable(version) << "(" << qPrintable(profile) << ")";
}
